package com.nf.mvc.view;

import com.nf.mvc.ViewResult;
import com.nf.mvc.util.FileUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import static com.nf.mvc.util.FileUtils.*;

public class FileViewResult extends ViewResult {
    private String filename;
    private InputStream input;

    public FileViewResult(String realPath) {
        this(getInputStreamFromRealPath(realPath), getFilename(realPath));
    }

    public FileViewResult(InputStream input, String filename) {
        this.input = input;
        this.filename = filename;
    }

    @Override
    public void render(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        resp.setContentType(getMediaType(this.filename));
        resp.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(getFilename(this.filename), "UTF-8"));
        copy(input, resp.getOutputStream());
    }
}
